package component.timeConsumingTask;

import com.google.common.util.concurrent.*;

import java.util.concurrent.Executors;

/**
 * 处理耗时任务，任务有返回值
 */

public class CallbackTaskCollector {

    /**
     * 使用谷歌 Guava管理线程池
     */
    static ListeningExecutorService guavaPool;

    static {
        guavaPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
    }

    private CallbackTaskCollector() {
    }

    /**
     * 添加任务
     */
    public static <R> void add(CallbackTask<R> executeTask) {

        ListenableFuture<R> future = guavaPool.submit(() -> {
            //执行传入的任务，此处用于处理耗时操作
            return executeTask.execute();
        });

        Futures.addCallback(future, new FutureCallback<>() {
            @Override
            public void onSuccess(R r) {
                //任务执行成功，回调
                executeTask.onBack(r);
            }

            @Override
            public void onFailure(Throwable t) {
                //任务执行失败，抛出异常
                executeTask.onException(t);
            }
        }, guavaPool);
    }

}
